<!-- 门诊挂号 -->
<script lang="ts" setup>
import { ref, reactive } from 'vue';
//引入字典数据api接口
import { getDictOptions } from '@/api/system/dict';
import { onMounted } from 'vue';
import { addPatient, getPatientByIdCard } from '@/api/doctor/patient';
import { calculateAge } from '@/utils/calculateAge';
import { generatePatientId } from '@/utils/generateId';
import { formatDate } from '@/utils/dateUtils';
import { addRegistration, getRegisteredDeptList, getRegisterItemList } from '@/api/doctor/registered';
import { dayjs, type ComponentSize } from 'element-plus'
import { getRegisteredScheduling } from '@/api/doctor/scheduling';
import { register } from 'module';
import { generateRegId } from '@/api/doctor/id';
import { useUserStore } from '@/store';
import { Flag } from '@element-plus/icons-vue/dist/types';
//定义性别字典项
let sex = ref([]);

onMounted(() => {
    const userId = useUserStore().user.userId;
    //将用户编号赋值到挂号对象中
    registered.value.userId = userId;
    //获取性别字典项
    getSex();
    //获取挂号费用字典项
    getRegisteredItem();
    //获取可挂号的科室
    getDeptList();
    //获取可挂号的科室
    getRegisteredScheduling(schedulingQueryZk.value);
})
//获取性别字典项
function getSex() {
    // 获取性别字典项
    getDictOptions("gender").then((response) => {
        const genderOptions = response.data;
        // 清空原有数组
        sex.value = [];
        // 循环添加每个选项
        genderOptions.forEach(option => {
            console.log("Adding option: " + option.value);
            sex.value.push(option);
            console.log("Option added: " + option.label);
        });
        console.log("Sex options: " + JSON.stringify(sex.value));
    }).catch(error => {
        console.error("获取性别选项失败:", error);
    });
}
//定义挂号费用数据
let registerItem = ref([]);
//获取挂号费用
function getRegisteredItem() {
    //调用查询挂号费用api接口
    getRegisterItemList().then(response => {
        //获取数据
        registerItem.value = response.data;
        console.log(registerItem.value, '挂号项目');
    }).catch(error => {
        ElMessage.warning('获取挂号费用失败');
        console.error("获取挂号费用失败:", error);
    });
}

// 患者信息数据模型
let patientInfo = ref({
    patientId: '', // 患者编号
    idcard: '', // 身份证号
    name: '',   // 患者姓名
    phone: '',  // 患者电话
    sex: 0, // 性别
    birthday: '', // 出生日期
    address: ''  // 地址信息
});

//定义查询身份证变量
const queryIdCard = ref('');
// 控制注册按钮显示
let showRegisterButton = ref(false);
//根据患者身份证号查询患者信息的点击事件处理函数
function loadPatientInfo() {
    //注册患者隐藏
    showRegisterButton.value = false;

    const idCard = queryIdCard.value.trim();
    if (!idCard) {
        ElMessage.warning('身份证号不能空');
        return;
    }
    // 校验身份证格式
    const idCardPattern = /^[1-9]\d{5}(18|19|20)\d{2}((0[1-9])|(1[0-2]))(([0-2][1-9])|10|20|30|31)\d{3}[\dXx]$/;
    if (!idCardPattern.test(idCard)) {
        ElMessage.warning('请输入正确的身份证号码格式');
        return;
    }
    // 获取患者信息
    getPatientByIdCard(queryIdCard.value).then(response => {
        if (response.data != null) {
            // 成功获得患者信息
            const patient = response.data;
            patientInfo.value.patientId = patient.patientId;
            patientInfo.value.idcard = patient.idCard;
            patientInfo.value.name = patient.name;
            patientInfo.value.phone = patient.phone;
            patientInfo.value.sex = patient.sex;
            patientInfo.value.birthday = patient.birthday;
            patientInfo.value.address = patient.address;

            ElMessage.success('查询成功');
            //将需要的患者信息添加到挂号对象中
            registered.value.patientId = patientInfo.value.patientId;
            registered.value.patientName = patientInfo.value.name;

        } else {
            // 患者信息未找到
            resetPatientForm();
            //可进行患者注册，注册按钮显示
            showRegisterButton.value = true;
            ElMessage.warning('未找到该患者信息');
        }
    });
    console.log("Patient info:", patientInfo.value);
    // ...
}

//如果出生日期发生改变，年龄也会改变，使用计算属性

const age = computed(() => {
    if (patientInfo.value.birthday) {
        return calculateAge(patientInfo.value.birthday);
    }
    return 0;
});

// 清空患者信息表单
function resetPatientForm() {
    patientInfo.value.idcard = '';
    patientInfo.value.name = '';
    patientInfo.value.phone = '';
    patientInfo.value.sex = 0;
    patientInfo.value.birthday = '';
    patientInfo.value.address = '';
}

//控制注册对话框显隐
const registerDialogVisible = ref(false);
//注册表单数据模型
const registerForm = ref({
    patientId: '',
    idcard: '',
    name: '',
    phone: '',
    sex: 0,
    birthday: '',
    address: ''
});

//提前清空注册患者信息
function clearRegisterForm() {
    registerForm.value.idcard = '';
    registerForm.value.name = '';
    registerForm.value.phone = '';
    registerForm.value.sex = 0;
    registerForm.value.birthday = '';
    registerForm.value.address = '';
}

//注册患者信息的点击事件处理程序
function openRegisterDialog() {
    // 点击时清空注册表单
    clearRegisterForm();
    // 生成患者编号
    const patientId = generatePatientId();
    // 将查询到的身份证号和生成的患者编号带入注册表单
    registerForm.value.idcard = queryIdCard.value;

    registerForm.value.patientId = patientId;
    // 显示对话框
    registerDialogVisible.value = true;
}

function submitRegister() {
    if (!registerForm.value.idcard || !registerForm.value.name || !registerForm.value.phone ||
        !registerForm.value.sex || !registerForm.value.birthday || !registerForm.value.address) {
        ElMessage.warning('请填写完整注册信息');
        return;
    }

    //构建完整的 Patient 对象
    const newPatient = {
        patientId: registerForm.value.patientId,
        name: registerForm.value.name,
        phone: registerForm.value.phone,
        idCard: registerForm.value.idcard,
        sex: registerForm.value.sex,
        birthday: formatDate(registerForm.value.birthday),
        address: registerForm.value.address
    };
    ElMessage.success('正在提交注册...');
    //调用新增患者api接口
    addPatient(newPatient).then((response => {
        //提示信息
        if (response.data == "添加患者信息成功！") {
            ElMessage.success(response.data);
        } else {
            ElMessage.error(response.data);
        }
    }))
    //添加完后隐藏
    registerDialogVisible.value = false;
}
//  选择挂号项目
function handleSelectRegisterItem(regItemId: number | string) {
    // 设置当前选中的挂号项目ID
    activeRegisterItem.value = regItemId;

    // 从 registerItem 中查找对应项
    const selectedItem = registerItem.value.find(
        item => item.regItemId === parseInt(regItemId.toString())
    );

    if (selectedItem) {
        // 更新挂号对象中的挂号项目信息
        registered.value.regItemId = selectedItem.regItemId.toString();
        registered.value.regItemAmout = Number(selectedItem.regItemFee).toFixed(2);
    } else {
        ElMessage.warning('未找到对应的挂号费用信息');
    }
}
//选中的挂号项目编号
let activeRegisterItem = ref<string>('');
// 根据 activeRegisterItem 获取选中的挂号费用项
const selectedRegisterItem = computed(() => {
    return registerItem.value.find(item => item.regItemId === parseInt(activeRegisterItem.value));
});


//定义可挂号科室列表
let deptList = ref([]);

//调用api接口获取可挂号的科室
function getDeptList() {
    getRegisteredDeptList().then(response => {
        deptList.value = response.data;
        console.log(deptList.value);
    }).catch(error => {

        ElMessage.error(error.message);
    })
}
//控制分页控件
let total = ref(0);
const size = ref<ComponentSize>('default');
const background = ref(false);
const disabled = ref(false);
//定义排班列表
let schedulingList = ref([]);

//定义查询排班的条件 
let schedulingQueryZk = ref({
    pageNum: 1,
    pageSize: 3,
    deptId: "",
    schedulingType: '',
    subsectionType: '',
    scheduingDay: ''
});
//定义挂号变量
let registered = ref({
    regId: '',
    patientId: '',
    patientName: '',
    userId: '',
    deptId: '',
    regItemId: '',
    regItemAmout: '',
    regNumber: 0,
    regStatus: 0,
    schedulingType: '',
    subsectionType: '',
    createTime: ''
})
// 搜索按钮点击事件处理函数
async function handleSearch() {
    // 这里可以添加具体的搜索逻辑，例如调用 API 获取数据
    console.log('SearchParams:', schedulingQueryZk.value);

    //将选中的科室，挂号类型，挂号时段，挂号时间赋值给挂号对象
    registered.value.deptId = schedulingQueryZk.value.deptId;
    registered.value.schedulingType = schedulingQueryZk.value.schedulingType;
    registered.value.subsectionType = schedulingQueryZk.value.subsectionType;
    //如果时间未选择，不转换 选择则时间转换 yyyy-MM-dd
    if (!schedulingQueryZk.value.scheduingDay == '') {
        schedulingQueryZk.value.scheduingDay = formatDate(schedulingQueryZk.value.scheduingDay);

        registered.value.createTime = schedulingQueryZk.value.scheduingDay;

        console.log('时间', schedulingQueryZk.value.scheduingDay);
    }
    //调用查询可挂号的排班数据 
    await getRegisteredScheduling(schedulingQueryZk.value).then(response => {
        console.log("查询排班数据", response);
        //获取总行数
        total.value = response.data.total;
        // schedulingList.value = response.data;
        schedulingList.value = response.data.list;
    });
}

// 重置按钮点击事件处理函数
function handleReset() {
    // 重置查询参数
    schedulingQueryZk.value = {
        pageNum: 1,
        pageSize: 3,
        deptId: "",
        schedulingType: '',
        subsectionType: '',
        scheduingDay: ''
    };
    // 可以在这里添加其他重置逻辑，例如清空表格数据等
    console.log('QueryParams reset:', schedulingQueryZk.value);
}

const handleSizeChange = (val: number) => {
    console.log(`${val} items per page`);
    schedulingQueryZk.value.pageSize = val;
    console.log("pageSize", schedulingQueryZk.value.pageSize);
    handleSearch();
}
const handleCurrentChange = (val: number) => {
    console.log(`current page: ${val}`)
    schedulingQueryZk.value.pageNum = val;
    console.log("pageNum", schedulingQueryZk.value.pageNum);
    handleSearch();
}
/**
 * 挂号信息校验函数（支持参数传入）
 * @param registered 挂号对象
 * @param activeRegisterItem 当前选中的挂号项目ID
 * @returns {boolean} 是否通过校验
 */
function registeredJudgeMent(registered: any, activeRegisterItem: any): boolean {
    // 判断需要挂号的患者信息是否存在
    if (!registered.patientId && !registered.patientName) {
        ElMessage.warning('请选择挂号患者');
        return false;
    }

    // 判断挂号费用是否选择
    if (!activeRegisterItem.value) {
        ElMessage.warning('请选择挂号费用');
        return false;
    }
    console.log("挂号费用", activeRegisterItem.value);

    // 判断挂号科室是否选择
    if (!registered.deptId) {
        ElMessage.warning("请选择挂号科室");
        return false;
    }

    // 判断挂号类型是否选择
    if (!registered.schedulingType) {
        ElMessage.warning("请选择挂号类型");
        return false;
    }

    // 判断挂号时段是否选择
    if (!registered.subsectionType) {
        ElMessage.warning("请选择挂号时段");
        return false;
    }

    // 判断挂号时间是否选择
    if (!registered.createTime) {
        ElMessage.warning("请选择挂号时间");
        return false;
    }

    // 所有校验通过
    return true;
}
//点击挂号费用按钮，添加挂号订单
async function addRegistered() {
    console.log("挂号", registered.value);
    //获取当前时间，为挂号的创建时间 这里使用这种格式2023-04-12 01:31:29
    registered.value.createTime = new Date(dayjs().format('YYYY-MM-DD HH:mm:ss'));
    console.log("挂号时间", registered.value.createTime);

    // 挂号前挂号信息判断
    if (!registeredJudgeMent(registered.value, activeRegisterItem)) {
        return;
    }
    //添加挂号信息时需要一个生成的挂号编号，调用生成挂号编号接口
    await generateRegId().then(response => {
        alert(1111)
        registered.value.regId = response.data;
        console.log("挂号编号", registered.value.regId);
    });
    console.log("挂号信息", registered.value);
    //添加挂号信息 调用添加挂号订单接口
    await addRegistration(registered.value).then(response => {
        if (response.data == "挂号成功") {
            ElMessage.success(response.data);
        } else {
            ElMessage.error("挂号失败");
        }
        //添加挂号成功后，清空挂号信息
        // registered.value = {};
    }).catch(error => {
        ElMessage.error(error.message);
    })
}

</script>
<template>
    <div class="app-container">
        <!-- 搜索部分 -->
        <div class="search-container">
            <el-form :model="patientInfo" label-width="120px">
                <!-- 第一行：身份证号和加载按钮 -->
                <el-form-item label="身份证号">
                    <el-input v-model="queryIdCard" placeholder="请输入患者身份证号" style="max-width: 400px;" />
                    <el-button type="primary" @click="loadPatientInfo" style="margin-left: 10px;">加载患者信息</el-button>
                    <el-button v-if="showRegisterButton" type="success" @click="openRegisterDialog"
                        style="margin-left: 10px;">
                        注册患者
                    </el-button>
                </el-form-item>
            </el-form>
        </div>
        <!-- 患者信息部分 -->
        <div class="patient-info-container">
            <el-form :model="patientInfo" label-width="90px">
                <!-- 第二行：身份证号、患者姓名、患者电话 -->
                <el-row :gutter="20">
                    <el-col :span="8">
                        <el-form-item label="* 身份证号">
                            <el-input v-model="patientInfo.idcard" placeholder="请输入患者身份证号" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="* 患者姓名">
                            <el-input v-model="patientInfo.name" placeholder="请输入患者姓名" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="* 患者电话">
                            <el-input v-model="patientInfo.phone" placeholder="请输入患者电话" />
                        </el-form-item>
                    </el-col>

                </el-row>

                <!-- 第行：性别、出生日期、患者年龄 -->
                <el-row :gutter="20">
                    <el-col :span="8">
                        <el-form-item label="性别">
                            <el-radio-group v-model="patientInfo.sex">
                                <el-radio v-for="option in sex" :key="option.value" :value="option.value"
                                    :label="option.label">
                                    {{ option.label }}
                                </el-radio>
                            </el-radio-group>
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="出生日期">
                            <el-date-picker v-model="patientInfo.birthday" type="date" placeholder="请选择出生日期" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="患者年龄">
                            <el-input v-model="age" readonly="true" placeholder="请输入患者年龄" />
                        </el-form-item>
                    </el-col>

                </el-row>
                <el-row :gutter="20">
                    <el-col>
                        <el-form-item label="地址信息">
                            <el-input v-model="patientInfo.address" type="textarea" placeholder="请输入患者地址信息" />
                        </el-form-item>
                    </el-col>
                </el-row>
            </el-form>
        </div>
        <!-- 注册患者的添加模态框 -->
        <el-dialog v-model="registerDialogVisible" title="注册新患者" width="50%">
            <el-form :model="registerForm" label-width="120px">
                <el-row :gutter="20">
                    <el-col :span="12">
                        <el-form-item label="身份证号">
                            <el-input v-model="registerForm.idcard" readonly />
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="姓名">
                            <el-input v-model="registerForm.name" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="电话">
                            <el-input v-model="registerForm.phone" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="性别">
                            <el-radio-group v-model="registerForm.sex">
                                <el-radio v-for="option in sex" :key="option.value" :label="option.value">
                                    {{ option.label }}
                                </el-radio>
                            </el-radio-group>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="出生日期">
                            <el-date-picker v-model="registerForm.birthday" type="date" placeholder="请选择出生日期" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="地址">
                            <el-input v-model="registerForm.address" type="textarea" />
                        </el-form-item>
                    </el-col>
                </el-row>
            </el-form>
            <template #footer>
                <el-button @click="registerDialogVisible = false">取消</el-button>
                <el-button type="primary" @click="submitRegister">提交注册</el-button>
            </template>
        </el-dialog>

        <!-- 挂号费用部分 -->
        <div class="register-item-container">
            <el-row :gutter="10">
                <el-col :span="2" v-for="item in registerItem" :key="item.regItemId">
                    <el-tag :type="activeRegisterItem === item.regItemId ? 'primary' : 'info'"
                        @click="handleSelectRegisterItem(item.regItemId)" class="register-tag">
                        {{ item.regItemName }}
                    </el-tag>
                </el-col>
                <el-col :span="2">
                    <el-button type="danger" @click="addRegistered" v-hasPerm="['doctor:registered:add']"
                        class="register-button">
                        <i-ep-search /> 挂号收费
                    </el-button>
                </el-col>
                <el-col :span="20">
                    <div v-if="selectedRegisterItem" class="register-details">
                        <p><strong>费用类型:</strong> {{ selectedRegisterItem.regItemName }}</p>
                        <p><strong>费用金额:</strong> {{ selectedRegisterItem.regItemFee.toFixed(2) }} 元</p>
                        <!-- <p><strong>描述:</strong> {{ selectedRegisterItem.description }}</p> -->
                    </div>
                </el-col>
            </el-row>
        </div>

        <!-- 选择已排班的科室挂号部分 -->
        <div class="registered-scheduling-dept-container">
            <!-- 查询已排班的科室条件 -->
            <el-row :gutter="20">
                <el-col :span="5">
                    <el-form-item label="所属科室">
                        <!-- 显示科室下拉框 -->
                        <el-select v-model="schedulingQueryZk.deptId" placeholder="请选择科室"
                            @change="getRegisteredDeptList">
                            <el-option v-for="item in deptList" :key="item.id" :label="item.name" :value="item.id" />
                        </el-select>
                    </el-form-item>
                </el-col>
                <el-col :span="5">
                    <el-form-item label="*挂号类型">
                        <dictionary v-model="schedulingQueryZk.schedulingType" type-code="scheduling_type"
                            placeholder="请选择挂号类型" />
                    </el-form-item>
                </el-col>
                <el-col :span="5">
                    <el-form-item label="*挂号时段">
                        <dictionary v-model="schedulingQueryZk.subsectionType" type-code="time_type"
                            placeholder="请选择挂号类型" />
                    </el-form-item>
                </el-col>
                <el-col :span="5">
                    <el-form-item label="*挂号时间">
                        <el-date-picker v-model="schedulingQueryZk.scheduingDay" type="date" placeholder="选择日期" />
                    </el-form-item>
                </el-col>
                <!-- 添加搜索和重置按钮 -->
                <el-col :span="3" style="text-align: right;">
                    <el-button type="primary" @click="handleSearch">搜索</el-button>
                    <el-button @click="handleReset">重置</el-button>
                </el-col>
            </el-row>
            <!-- 选择可以挂号已排班科室显示的表格 -->
            <el-table :data="schedulingList" border style="width: 100%;">
                <el-table-column prop="id" label="科室ID" width="472" align="center"></el-table-column>
                <el-table-column prop="name" label="科室名称" width="472" align="center"></el-table-column>
                <el-table-column prop="schedulingCount" label="当前号数" width="472" align="center"></el-table-column>
            </el-table>


            <div class="demo-pagination-block">
                <el-pagination v-model:current-page="schedulingQueryZk.pageNum" :page-size="schedulingQueryZk.pageSize"
                    :page-sizes="[3, 5, 10, 20]" :size="size" :disabled="disabled" :background="background"
                    layout="total, sizes, prev, pager, next, jumper" :total="total" @size-change="handleSizeChange"
                    @current-change="handleCurrentChange" />
            </div>


        </div>
    </div>
</template>
<style scoped>
.app-container {
    padding: 20px;
}

.el-row {
    margin-bottom: 14px;
}

.search-container {
    margin-bottom: 20px;
    /* 增加搜索部分与患者信息之间的间距 */
}

.patient-info-container {
    /* patient-info-container 的样式 */
    margin-top: 20px;
    padding: 20px 20px 0px;
    border: 1px solid #ebeef5;
    border-radius: 4px;
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
    background-color: white;
    background-size: 100% 100%;
    background-repeat: no-repeat;
    box-sizing: border-box;
}

.el-row {
    margin-bottom: 14px;
}

.register-item-container {
    /* register-item-container 的样式 */
    margin-top: 20px;
    padding: 20px 20px 0px;
    border: 1px solid #ebeef5;
    border-radius: 4px;
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
    background-color: white;
    background-size: 100% 100%;
    background-repeat: no-repeat;
    box-sizing: border-box;
}

/* 调整按钮样式 */
.register-button {
    margin-left: 800px;
    width: 100%;
}

/* 统一挂号项宽度并添加边框 */
.register-tag {
    width: 100%;
    text-align: center;
    height: 100%;
    font-size: 14px;
    color: black;
    border: 1px solid #dcdcdc;
    margin-right: 0;
    /* 移除默认的右边距 */
    margin-bottom: 5px;
    /* 添加底部边距以区分不同行 */
}

/* 挂号费用详情样式 */
.register-details {
    width: 1420px;
    border: 1px solid #dcdcdc;
    padding: 10px;
    margin-top: 10px;
}

/* 挂号科室样式 */
.registered-scheduling-dept-container {
    margin-top: 20px;
    padding: 20px 20px 0px;
    border: 1px solid #ebeef5;
    border-radius: 4px;
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
    background-color: white;
    background-size: 100% 100%;
    background-repeat: no-repeat;
    box-sizing: border-box;
}
</style>
